package controller

import (
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"good.house/internal/dto/request"
	userresponse "good.house/internal/dto/response"
	"good.house/internal/service"
	"good.house/internal/utils"
	innerValidator "good.house/internal/validator"
	"good.house/pkg/response"
)

type UserController struct {
	service *service.UserService
}

func NewUserController(service *service.UserService) *UserController {
	return &UserController{
		service: service,
	}
}

// @Summary 用户注册
// @Description 用户注册接口
// @Tags 用户
// @Accept  json
// @Produce  json
// @Param    data  body  request.RegisterRequest  true  "注册参数"
// @Success 200 {object} response.UserRegResponse
// @Router /api/reqister [post]
func (ctl *UserController) Register(ctx *gin.Context) {
	var req request.RegisterRequest

	if err := ctx.ShouldBindBodyWith(&req, binding.JSON); err != nil {
		if errs, ok := innerValidator.TranslateValidateError(err); ok {
			response.Error(ctx, strings.Join(errs, ";"))
			return
		}
		response.Error(ctx, err.Error())
		return
	}

	if !innerValidator.IsPhoneNumber(req.Mobile) {
		response.Error(ctx, "手机号格式错误")
		return
	}

	err := ctl.service.Register(&req)

	if err != nil {
		response.Error(ctx, err.Error())
	} else {
		response.Success(ctx, "注册成功", nil)
	}

}

// @Summary 用户登录
// @Description 用户登录接口
// @Tags 用户
// @Accept  json
// @Produce  json
// @Param    data  body  request.LoginRequest  true  "登录参数"
// @Success 200 {object} response.UserLoginResponse
// @Router /api/login [post]
func (ctl *UserController) Login(ctx *gin.Context) {
	var req request.LoginRequest

	if err := ctx.ShouldBindBodyWith(&req, binding.JSON); err != nil {

		if errs, ok := innerValidator.TranslateValidateError(err); ok {
			response.Error(ctx, strings.Join(errs, ";"))
			return
		}

		response.Error(ctx, err.Error())
		return
	}

	cfg := utils.GetConfigByGinContext(ctx)

	if cfg == nil {
		response.Error(ctx, "发生未知错误")
	}

	user, token, err := ctl.service.Login(&req, cfg.JWt.SecretKey)

	if err != nil {
		response.Error(ctx, err.Error())
	} else {
		if user.Username != "" {
			response.Success(ctx, "登录成功", &userresponse.UserData{
				Username: user.Username,
				NickName: user.Nickname,
				Token:    token,
			})
		} else {
			response.Error(ctx, "用户不存在")
		}
	}
}
